<template>
  <div class="article-page">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>面经后台</el-breadcrumb-item>
      <el-breadcrumb-item>面经管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card shadow="never" border="false">
      <template #header>
        <div class="header">
          <span>共 {{ total }} 条记录</span>
          <el-button
            @click="openDrawer('add')"
            icon="el-icon-plus"
            size="small"
            type="primary"
            round
          >
            添加面经
          </el-button>
        </div>
      </template>

      <!-- 表格主体
      1. el-table表示表格主体
        需要使用:data绑定整个表格数据，类型是对象数组（[{},{},{},...]），发请求获取
      2. el-table-column表示表格的列:
        2.1 使用prop属性搭配对象中的键名去读取并渲染数据
        2.2 使用label属性定义表格的列明
        2.3 使用width属性定义表格的宽度
       -->
      <el-table :data="list" style="width: 100%">
        <el-table-column prop="stem" label="标题" width="400">
        </el-table-column>
        <el-table-column prop="creator" label="作者"> </el-table-column>
        <el-table-column prop="likeCount" label="点赞"> </el-table-column>
        <el-table-column prop="views" label="浏览数"> </el-table-column>
        <el-table-column prop="createdAt" label="更新时间" width="200">
        </el-table-column>
        <el-table-column label="操作" width="120px">
          <!--
            难点：我们使用的是element-ui提供的表格，表格的数据渲染是内部使用了v-for实现的，所以表格外部拿不到id
            问题：如何获取到表格内部每一行的id?
            解决：由于element-ui提供的表格是使用具名插槽展示内容的，因此可以使用插槽传值的方式得到表格行的id
            底层逻辑：
            <div v-for="item in list" :key="item.id">
              <slot :row="item"></slot>
            </div>
            解释：#default="scope"
            scope表示具名插槽上的数据对象，可以获取到插槽中的数据
           -->
          <template #default="{ row }">
            <div class="actions">
              <i
                class="el-icon-view"
                @click="openDrawer('preview', row.id)"
              ></i>
              <i
                class="el-icon-edit-outline"
                @click="openDrawer('edit', row.id)"
              ></i>
              <i class="el-icon-delete" @click="del(row.id)"></i>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页导航
        @current-change 监听当前页码变化
        :current-page   设置当前页码
        :page-size      每页条数
        total           总条数
        layout          布局容器
       -->
      <el-pagination
        background
        @current-change="handleCurrentChange"
        :current-page="current"
        :page-size="pageSize"
        layout="prev, pager, next"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 抽屉效果
    :visible.sync 使用布尔值控制抽屉显示隐藏，true显示，false隐藏
    :direction    抽屉打开的方向 rtl 从右往左开（默认）
    :before-close 关闭抽屉的操作
    size          抽屉大小 50% 浏览器视口的50%
     -->
    <el-drawer
      :visible.sync="isShowDrawer"
      :before-close="handleClose"
      :title="drawerTitle"
      direction="rtl"
      size="45%"
    >
      <div v-if="drawerType === 'preview'" class="article-preview">
        <h5>{{ form.stem }}</h5>
        <div v-html="form.content"></div>
      </div>

      <!--
        el-form校验:
        1. 准备一个数据对象，让对象的属性和表单元素v-model绑定
        2. 设置el-from
            :model="数据对象"，告诉el-form校验哪个数据对象
            :rules="校验规则"，告诉el-form如何校验数据
        3. 设置el-form-item
            prop="字段名"
       -->
      <el-form
        v-else
        :model="form"
        :rules="rules"
        ref="form"
        label-width="80px"
      >
        <el-form-item label="标题" prop="stem">
          <el-input v-model="form.stem" placeholder="输入面经标题"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <quill-editor
            v-model="form.content"
            @blur="$refs.form.validateField('content')"
          ></quill-editor>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit">确认</el-button>
          <el-button @click="handleClose">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
// require styles
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { quillEditor } from 'vue-quill-editor'
import { createArticle, getArticleDetail, getArticleList, removeArticle, updateArticle } from '@/api/article'
export default {
  components: {
    quillEditor
  },
  name: 'article-page',
  data () {
    return {
      current: 1,
      pageSize: 10,
      total: 0,
      list: [],
      isShowDrawer: false,
      drawerType: '',
      form: {
        stem: '',
        content: ''
      },
      rules: {
        stem: [{ required: true, message: '请输入面经标题', trigger: 'blur' }],
        content: [{ required: true, message: '请输入面经标题', trigger: 'blur' }]
      }

    }
  },
  created () {
    this.initData()
  },

  methods: {
    async initData () {
      const { data } = await getArticleList({
        current: this.current,
        pageSize: this.pageSize
      })
      this.list = data.rows
      this.total = data.total
      console.log(data)
    },

    handleClose () {
      // 抽屉在关闭前需要先重置数据
      // this.$refs.articleForm.resetFields()
      // 当有form时才重置 form表单
      this.$refs.articleForm?.resetFields()
      this.isShowDrawer = false
    },
    // 切换页码:val 更新后的页码
    handleCurrentChange (val) {
      // console.log(val)
      // 更新页码
      this.current = val
      // 请求指定页数据并覆盖渲染
      this.initData()
    },

    async del (id) {
      await removeArticle(id)
      this.$message.success('删除成功')
      this.initData()
    },

    async openDrawer (type, id) {
      // console.log(type, id)
      this.drawerType = type
      this.isShowDrawer = true

      if (type !== 'add') {
        const res = await getArticleDetail(id)
        this.form = {
          ...res.data
        }
      }
    },

    async submit () {
      try {
        // 校验表单
        await this.$refs.form.validate()
        // 如何区分, 当前是 编辑 还是 添加
        if (this.drawerType === 'add') {
          // 发送请求
          await createArticle(this.form)
          // 添加提示 $message.success
          this.$message.success('添加成功')
        }
        if (this.drawerType === 'edit') {
          // 发送的是编辑的请求
          const { id, stem, content } = this.form
          await updateArticle({ id, stem, content })
          this.$message.success('修改成功')
        }
        // 无论是修改还是添加, 都会回到第一页, 重置页码
        this.current = 1
        // 重新渲染
        this.initData()
        // 关闭弹框
        this.handleClose()
      } catch (e) {
        console.log(e)
      }
    }
  },
  computed: {
    drawerTitle () {
      let title = ''
      if (this.drawerType === 'add') {
        title = '添加面经'
      } else if (this.drawerType === 'preview') {
        title = '预览面经'
      } else {
        title = '编辑面经'
      }
      return title
    }
  }
}
</script>

<style lang="scss" scoped>
.el-card {
  margin-top: 25px;
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-right: 16px;
  }
  .actions {
    font-size: 18px;
    display: flex;
    justify-content: space-around;
    color: #666;
    > i:hover {
      color: rgba(114, 124, 245, 1);
      cursor: pointer;
    }
  }
}
.el-pagination {
  margin-top: 20px;
  text-align: center;
}
.el-breadcrumb {
  margin-top: 10px;
}
.el-form {
  padding-right: 40px;
}
.quill-editor {
  ::v-deep .ql-editor {
    height: 300px;
  }
}
.el-rate {
  padding: 10px 0;
}
.article-preview {
  padding: 0 40px 40px 40px;
  > h5 {
    font-size: 20px;
    color: #666;
    border-bottom: 1px dashed #ccc;
    padding-bottom: 30px;
    margin: 0 0 20px 0;
  }
}
</style>
